<?php
/**
*description:入库管理
*author:李飞@天众科技
*time:2016/12/27
*/

namespace Admin\Controller;
use Think\Controller;
class OrderController extends CommonController {
	//添加
    public function booksInfoCateAdd(){
		$m=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
        if(!IS_POST) exit;
        $ck=A('CheckInput'); 
		$data['goods_no']=I('goods_no');
		$data['goods_name']=I('goods_name');
		$data['goods_brand']=I('goods_brand');
		$data['goods_marque']=I('goods_marque');
		
		$data['goods_spec']=I('goods_spec');
		$data['net_weight']=I('net_weight');
		$data['gross_weight']=I('gross_weight');
		$data['bar_code']=I('bar_code');
		$data['goods_tax']=I('goods_tax');
		$data['receive_amount']=I('receive_amount');
		$data['price']=I('price');
		$data['unit1']=I('unit1');
		$data['unit2']=I('unit2');
		$data['currency']=I('currency');
		$data['source_no']=I('source_no');
		$data['country_code']=I('country_code');
		$data['add_time']=time();
		$data['status']=1;
		$data['update_time']=time();
		//重复判断
		$map['goods_no']=I('goods_no');
		$duplicate=$m->where($map)->find();
		if($duplicate){
			$return['message']='商品编码已经存在';
            $return['status']=false;
            $this->ajaxReturn($return);
		}
		
		if (!empty($_FILES)){
			$config = array(
				'maxSize'    =>    3145728,    
				'savePath'   =>    '/Import/',    
				'saveName'   =>    array('uniqid',''),    
				'exts'       =>    array('jpg','jpeg','png','gif'),    
				'autoSub'    =>    true,    
				'subName'    =>    array('date','Ymd'),);
			$upload = new \Think\Upload($config);// 实例化上传类
			$info   =   $upload->upload();    
			if(!$info){// 上传错误提示错误信息        
				$this->error($upload->getError());    
			}
			$extension=$info['goods_pic']['ext'];
			$file_name='./Uploads'.$info['goods_pic']['savepath'].$info['goods_pic']['savename'];
			$data['goods_pic']=$file_name;
		}
        $insertId=$m->add($data);
		// echo $m->getlastsql();
        if(!$insertId){
            $return['message']='添加失败';
            $return['status']=false;
            $this->ajaxReturn($return);
        }else{
			//推送云仓库存
			$id=$insertId;
			$ao=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
			$map_ao['id']=$id;
			$ao_list=$ao->field('goods_name,price goods_price,receive_amount goods_number,goods_no goods_sn,source_no goods_pn,net_weight,gross_weight,3 is_cross,goods_tax g_tax')->where($map_ao)->find();
			// echo $ao->getlastsql();
			$url=C('BASE_CONFIG.yuncang_goods');//云仓同步添加商品接口
			$token=C('BASE_CONFIG.yuncang_token');//云仓同步添加商品接口
			$push=A('Pushsendapi');
			$push_list['warehouse_code']=session('warehouse_code');
			$push_list['token']=$token;
			$push_list['type']='insert';
			$push_list['data'][0]=$ao_list;
			// var_dump($push_list);
			$res = $push->push($url,$push_list);
			// echo "<pre>";
			// var_dump($res);
			// var_dump($push_list);
			// die;
			if(!$res['status']){//失败
				$return['status']=0;
				$return['message']='推送云仓数据失败，请重新推送';
				$this->ajaxReturn($return);
			}else{
				$ao->where($map_ao)->setField('push_yuncang_status',1);//更新推送状态
				$return['message']='添加成功!';
				$return['status']=true; 
				$this->ajaxReturn($return);
			}
        }
    }
	//更新
    public function booksInfoCateSave(){
		
		$m=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
        if(!IS_POST) exit; 
        $ck=A('CheckInput');

		$data['goods_name']=I('goods_name');
		$data['goods_brand']=I('goods_brand');
		$data['goods_marque']=I('goods_marque');

		$data['goods_spec']=I('goods_spec');
		$data['net_weight']=I('net_weight');
		$data['gross_weight']=I('gross_weight');
		$data['bar_code']=I('bar_code');
		$data['goods_tax']=I('goods_tax');
		$data['receive_amount']=I('receive_amount');
		$data['price']=I('price');
		$data['unit1']=I('unit1');
		$data['unit2']=I('unit2');
		$data['currency']=I('currency');
		$data['source_no']=I('source_no');
		$data['country_code']=I('country_code');
		$data['update_time']=time();
		$id=I('id');
        $map['id']=$id;
		if (!empty($_FILES)){
			$config = array(
				'maxSize'    =>    3145728,    
				'savePath'   =>    '/Import/',    
				'saveName'   =>    array('uniqid',''),    
				'exts'       =>    array('jpg','jpeg','png','gif'),    
				'autoSub'    =>    true,    
				'subName'    =>    array('date','Ymd'),);
			$upload = new \Think\Upload($config);// 实例化上传类
			$info   =   $upload->upload();    
			if(!$info) {// 上传错误提示错误信息        
				$this->error($upload->getError());    
			}
			$extension=$info['goods_pic']['ext'];
			$file_name='./Uploads'.$info['goods_pic']['savepath'].$info['goods_pic']['savename'];
			$data['goods_pic']=$file_name;
		}
        $result=$m->where($map)->save($data);
        if(false===$result){
            $return['message']='更新信息失败';
            $return['status']=false;
            $this->ajaxReturn($return);
        }else{
			//推送云仓库存
			$ao=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
			$map_ao['id']=$id;
			$ao_list=$ao->field('goods_name,price goods_price,receive_amount goods_number,goods_no goods_sn,source_no goods_pn,net_weight,gross_weight,3 is_cross,goods_tax g_tax')->where($map_ao)->find();
			// echo $ao->getlastsql();
			$url=C('BASE_CONFIG.yuncang_goods');//云仓同步添加商品接口
			$token=C('BASE_CONFIG.yuncang_token');//云仓同步添加商品接口
			$push=A('Pushsendapi');
			$push_list['warehouse_code']=session('warehouse_code');
			$push_list['token']=$token;
			$push_list['type']='edit';
			$push_list['data'][0]=$ao_list;
			// var_dump($push_list);
			$res = $push->push($url,$push_list);
			// echo "<pre>";
			// var_dump($res);
			// var_dump($push_list);
			if(!$res['status']){//失败
				$return['status']=0;
				$return['message']='推送云仓数据失败，请重新推送';
				$this->ajaxReturn($return);
			}else{
				$ao->where($map_ao)->setField('push_yuncang_status',1);//更新推送状态
				$return['message']='更新信息成功!';
				$return['status']=true; 
				$this->ajaxReturn($return);
			}
        }
    }
	//详情
	public function get_booksInfoCate(){
		
        $ck=A('CheckInput');
		//参数验证
        $goods_no=$ck->in('商品编号','goods_no','ennumstr','',0,0);
        $goods_name=$ck->in('商品名称','goods_name','cnennumstr','',0,0);
		$manua_id=$ck->in('账册编号','manua_id','cnennumstr','',0,0);
        $page=$ck->in('当前页','page','intval','1',0,0);
        $rows=$ck->in('每页记录数','rows','intval','',0,0);
		$status=I('status');
		//排序
        $sort=$ck->in('排序','sort','cnennumstr','id',0,0);
        $order=$ck->in('规则','order','cnennumstr','desc',0,0);
		//搜索条件
		$map=array();
		$cate_id=I('cate_id','','trim');
		if(!empty($cate_id)){
			$detail=M('BooksCate',C('DB_PRS'),C('DB_DEPOT'))->field('code')->find($cate_id);//详情
			$map['manua_id']=$detail['code'];
		}
		
		!empty($goods_no)?$map['goods_no']=array('like','%'.$goods_no.'%'):'';
        !empty($goods_name)?$map['goods_name']=array('like','%'.$goods_name.'%'):'';
		!empty($manua_id)?$map['manua_id']=$manua_id:'';
		
		//获取数据
        $data=getTable('ArrivalOrder',$map,$page,$rows,$sort,$order,$status);

        $this->ajaxReturn($data);
    }
	//////////////////////////////////////////////////////
	//审核账册详情
    public function examineBooksInfoCate(){
		$return=tableExamine('ArrivalOrder');
        $this->ajaxReturn($return);
    }
	//删除
    public function booksInfoCateDel(){
		//推送云仓库存
		$id=I('id');
		$ao=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		$map_ao['id']=array('in',$id);
		$ao_list=$ao->field('goods_no goods_sn')->where($map_ao)->select();

		$url=C('BASE_CONFIG.yuncang_goods');//云仓同步添加商品接口
		$token=C('BASE_CONFIG.yuncang_token');//云仓同步添加商品接口
		$push=A('Pushsendapi');
		$push_list['warehouse_code']=session('warehouse_code');
		$push_list['token']=$token;
		$push_list['type']='delete';
		$push_list['data']=$ao_list;

		$res = $push->push($url,$push_list);
			// echo "<pre>";
			// var_dump($res);
			// var_dump($push_list);
			// die;
		if(!$res['status']){//失败
			$return['status']=0;
			$return['message']='推送云仓数据失败，请重新推送';
			$this->ajaxReturn($return);
		}else{
			$return=tableDel('ArrivalOrder');
			$this->ajaxReturn($return);
		}
    }
	//清空回收站
    public function booksInfoCateClear(){
		$return=tableClear('ArrivalOrder');
        $this->ajaxReturn($return);
    }
	//恢复回收站数据
    public function booksInfoCateUndo(){
		$return=tableUndo('ArrivalOrder');
        $this->ajaxReturn($return);
    }
	public function getbooks(){
		$m=M('Books',C('DB_PRS'),C('DB_DEPOT'));

        $ck=A('CheckInput');
		//参数验证
        $page=$ck->in('当前页','page','intval','1',0,0);
        $rows=$ck->in('每页记录数','rows','intval','',0,0);
		//排序
        $sort=$ck->in('排序','sort','cnennumstr','id',0,0);
        $order=$ck->in('规则','order','cnennumstr','desc',0,0);

		$map['status']=1;
		
		$count=$m->where($map)->count();
        $info=$m->where($map)->page($page,$rows)->order($sort.' '.$order)->select();

		//获取数据
        $data['total']=$count;
        $data['rows']=$info;
		
        $this->ajaxReturn($data);
	}
	//流水单号
	public function ajax_orderno(){
		$t_no=serialNumber('ProductOrder');//流水号
		$order_no='PM'.date('Ymd',time()).$t_no;//流水单号
		$return['status']=1;
		$return['order_no']=$order_no;
		$this->ajaxReturn($return);
	}
	//批次号
	public function ajax_batchno(){
		$batch_no='PM'.date('YmdHis',time());//批次号
		$return['status']=1;
		$return['batch_no']=$batch_no;
		$this->ajaxReturn($return);
	}
	//产品编码
	public function ajax_goodsno(){
		$warehouse_code=session('warehouse_code');
		$goods_no=$warehouse_code.date('YmdHis',time());//产品编码
		$return['status']=1;
		$return['goods_no']=$goods_no;
		$this->ajaxReturn($return);
	}
	//产品料号
	public function ajax_sourceno(){
		$source_no=date('YmdHis',time());//产品料号
		$return['status']=1;
		$return['source_no']=$source_no;
		$this->ajaxReturn($return);
	}
	
    public function index(){
		
		$this->redirect('arrival');
    }
	//入库单
	public function printconfirmarrival(){
		$m=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		$u=M('Unit',C('DB_PRS'),C('DB_DEPOT'));
		$id=I('id');
		$cid=I('cid');//参数二
		if(empty($cid)){
			$m=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
			$detail=$m->where(array('id'=>$id))->find();
			$list=$m->where(array('order_no'=>$detail['order_no']))->select();
			// dump($list);
			foreach($list as $k=>$v){
				if($v['confirm_status']<2){
					$return['status']=0;
					$return['message']="入库单存在实收数据未确认，请先确认实收数据再打印！";
					$this->ajaxReturn($return);
				}else{
					$return['status']=1;
					$return['message']="验证通过！";
					$this->ajaxReturn($return);
				}
			}
		}
		$detail=$m->where(array('id'=>$id))->find();
		$list=$m->where(array('order_no'=>$detail['order_no']))->select();
		$count_receive_amount=0;
		$count_unit2_count=0;
		
		foreach($list as $k=>$v){
			$unit1_info=$u->where(array('unit_no'=>$v['unit1']))->find();
			$unit2_info=$u->where(array('unit_no'=>$v['unit2']))->find();
			$list[$k]['unit1_name']=$unit1_info['unit_name'];
			$list[$k]['unit2_name']=$unit2_info['unit_name'];
			$count_receive_amount+=$v['receive_amount'];
			$count_unit2_count+=$v['unit2_count'];
		}
		// echo $m->getlastsql();
		$this->assign('count_receive_amount',$count_receive_amount);
		$this->assign('count_unit2_count',$count_unit2_count);
		$this->assign('detail',$detail);
		$this->assign('list',$list);
		$this->display();
	}
	//原料采购单详情
	/* public function purchasingorderInfo_iframe(){
		$id=I('id');//参数一
		// $cid=I('cid');//参数二
		$iframeUrl=U('purchasingorderInfo',array('id'=>$id,array('cid'=>1)));
		$this->assign('iframeUrl',$iframeUrl);
		$this->display('purchasingorder_iframe');
    } */
	//采购入库单详情
	public function orderArrivalinfo(){
		$this->display();
    }
	//原料采购单详情
	public function purchasingorderInfo(){
		$this->display();
    }
	//原料采购单
	public function purchasingorder_iframe(){
		$iframeUrl=U('purchasingorder');
		$this->assign('iframeUrl',$iframeUrl);
		$this->display();
    }

	//原料采购单
	public function purchasingorder(){
		$section_lists=sectionlist();//部门列表
		$unit_lists=unitlist();//单位列表
		$personnel_lists=personnellist();//员工列表
		$warehouse_lists=depot_list();//仓库列表
		$contacts_company_lists=contactsCompanylist();//往来单位
		
		$this->assign('section_lists',json_encode($section_lists));
		$this->assign('unit_lists',json_encode($unit_lists));
		$this->assign('personnel_lists',json_encode($personnel_lists));
		$this->assign('warehouse_lists',json_encode($warehouse_lists));
		$this->assign('contacts_company_lists',json_encode($contacts_company_lists));
		
		$contacts_company_list=contactsCompanylist();//往来单位
		
		$personnel_list=personnellist();//员工列表
		$unit_list=unitlist();//单位列表
		$depotlist=depot_list();
		$section_list=sectionlist();//部门列表
		// $this->assign('curr_personnel',$curr_personnel);
		$this->assign('contacts_company_list',$contacts_company_list);
		$this->assign('section_list',$section_list);
		$this->assign('personnel_list',$personnel_list);
		$this->assign('depotlist',$depotlist);
		$this->assign('unit_list',$unit_list);
		
		$this->display();
    }
	//商品批次明细
	public function goods_batch_list(){
		$m=M('Goods',C('DB_PRS'),C('DB_DEPOT'));
		$id=I('id');
		$goods_info=$m->find($id);
		$this->assign('goods_info',$goods_info);
		$this->display();
    }
	public function arrival(){
		$this->display();
    }
	public function arrival_log(){
		$this->display();
    }
	//监盘计划
	public function plan_iframe(){
		$id=I('id');//参数一
		
		$iframeUrl=U('printmonitordetail',array('id'=>$id));
		$this->assign('iframeUrl',$iframeUrl);
		$this->display('iframe');
	}
	//监盘计划--详细
	public function printmonitordetail(){
		$id=I('id')?I('id'):0;
		if($id){
			$m=M('ArrivalOrderPlan',C('DB_PRS'),C('DB_DEPOT'));
			$detail=$m->find($id);
			
			$n=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
			$listrows=10;
			
			$p=I('p')?I('p'):1;
			$firstrow=($p-1)*$listrows;
			$count   = $n->where(array('order_no'=>$detail['order_no']))->count();// 查询满足要求的总记录数
			$Page    = new \Think\Page($count,$listrows);// 实例化分页类 传入总记录数和每页显示的记录数(25)
			$show    = $Page->show();// 分页显示输出
			
			$list   = $n->where(array('order_no'=>$detail['order_no']))->select();// 查询满足要求的记录数

			foreach($list as $k=>$v){
				$list[$k]['currency_c']=M('Coin',C('DB_PRS'),C('DB_DEPOT'))->where('coin_code="'.$v['currency'].'"')->find();
				$list[$k]['country_c']=M('Country',C('DB_PRS'),C('DB_DEPOT'))->where('country_code="'.$v['country_code'].'"')->find();
				// $list[$k]['goods_name']=M('MergeGoods')->where('goods_no="'.$v['goods_no'].'"')->find();
			}
			$countlist=21;//初始行数
			$listcount=count($list);
			
			$this->assign("listc",$countlist-$listcount);//剩余行数
			$this->assign("list",$list);
			$this->assign("detail",$detail);
			$this->assign('page',$show);// 赋值分页输出
		}else{
			$this->error('请关联计划单id');
		}
		
		$this->display();
	}
	//入库单推到货通知
    public function purchasingorder_inbound2(){
		$s=M('PurchasingOrder',C('DB_PRS'),C('DB_DEPOT'));
		$m=M('PurchasingOrderDetail',C('DB_PRS'),C('DB_DEPOT'));
		$ss=M('ArrivalOrderPlan',C('DB_PRS'),C('DB_DEPOT'));
		$mm=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		$n=M('Goods',C('DB_PRS'),C('DB_DEPOT'));
        if(!IS_POST) exit;
        $ck=A('CheckInput');
		$id=$ck->in('入库单id','id','string','',1,0);
        if(empty($id)) exit;//为空
        $arr=explode(',', $id);
		$map['id']=array('in',$arr);
		$plan_list=$s->where($map)->select();
		foreach($plan_list as $ks=>$vs){
			if($vs['inbound_status']==1){
					continue;//已经入库，则继续循环
			}
			// $arrival_goods=$m->where(array('plan_id'=>$vs['id']))->select();
			$arrival_goods=$m->alias('m')->field('m.id,m.bar_code,m.plan_id,m.weight,m.price,m.conforming_p,m.nonconforming_p,m.scrap_one,b.manua_id as manual_id,b.goods_no,b.goods_name,b.source_no,b.goods_spec,b.current_type,b.unit1,b.source,b.goods_spec')->join('__BOOKS__ as b on m.books_id=b.id')->where(array('m.plan_id'=>$vs['id']))->select();
			foreach($arrival_goods as $k=>$v){
				$receive_amount=$v['weight'];//实收数量
				$conforming_p=$v['conforming_p'];//合格品数量
				$nonconforming_p=$v['nonconforming_p'];//残次品数量
				$scrap_one=$v['scrap_one'];//报废品数量
				//where唯一条件:商品编码相同，账册编码相同
				$where['goods_no']=$v['goods_no'];
				$where['manua_id']=$v['manual_id'];
				$res=$n->where($where)->find();
				
				if($res){//库存中已经有此商品，则更新库存数据
					$data_n=array();
					$data_n['amount']=array('exp',"amount+$receive_amount");
					$data_n['conforming_p']=array('exp',"conforming_p+$conforming_p");
					$data_n['nonconforming_p']=array('exp',"nonconforming_p+$nonconforming_p");
					$data_n['scrap_one']=array('exp',"scrap_one+$scrap_one");
					//价格-平均价--总价/总数量
					$data_n['goods_price']=($res['goods_price']*$res['amount']+$v['receive_amount']*$v['price'])/($res['amount']+$v['receive_amount']);
					$ress=$n->where($where)->save($data_n);
					// echo $n->getlastsql();
					if($ress!==false){
						//更新批次详情
						$this->arrivalorderInfo($vs['purchasing_no'],$vs['batch_no'],$v);
						$mm->where(array("order_no"=>$vs['purchasing_no']))->setField('bar_code',$res['bar_code']);//更新条形码
						continue;
					}else{
						$this->error($v['goods_name'].'| 入库失败！');
					}
				}else{//库存中没有此商品,则添加此商品数据入库存
					$data=array();
					$data['source_no']=$v['source_no'];
					$data['goods_name']=$v['goods_name'];
					$data['goods_no']=$v['goods_no'];
					$data['bar_code']=$v['bar_code'];
					$data['amount']=$receive_amount;
					$data['conforming_p']=$v['conforming_p'];
					$data['nonconforming_p']=$v['nonconforming_p'];
					$data['scrap_one']=$v['scrap_one'];
					$data['goods_price']=$v['price'];
					$data['goods_cate']=1;
					$data['manua_id']=$v['manual_id'];
					$data['goods_spec']=$v['goods_spec'];
					
					$resss=$n->add($data);
					// echo $n->getlastsql();
					// die;
					if($resss){
						//更新批次详情
						$this->arrivalorderInfo($vs['purchasing_no'],$vs['batch_no'],$v);
						
						continue;
					}else{
						$this->error($v['goods_name'].'| 入库失败！');
					}
				}
			}
			// $s->where(array("id"=>$vs['id']))->setField('inbound_status',1);//更新入库状态
			
			// echo $s->getlastsql();
		}
		

        $return['info']='推送成功!';
        $return['status']=true;    
        $this->ajaxReturn($return);
    }
	//原料入库
    public function purchasingorder_inbound(){
		$s=M('PurchasingOrder',C('DB_PRS'),C('DB_DEPOT'));
		$m=M('PurchasingOrderDetail',C('DB_PRS'),C('DB_DEPOT'));
		$ss=M('ArrivalOrderPlan',C('DB_PRS'),C('DB_DEPOT'));
		$mm=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		$n=M('Goods',C('DB_PRS'),C('DB_DEPOT'));
        if(!IS_POST) exit;
        $ck=A('CheckInput');
		$id=$ck->in('入库单id','id','string','',1,0);
        if(empty($id)) exit;//为空
        $arr=explode(',', $id);
		$map['id']=array('in',$arr);
		$plan_list=$s->where($map)->select();
		foreach($plan_list as $ks=>$vs){
			if($vs['inbound_status']==1){
					continue;//已经入库，则继续循环
			}
			// $arrival_goods=$m->where(array('plan_id'=>$vs['id']))->select();
			$arrival_goods=$m->alias('m')->field('m.id,m.bar_code,m.plan_id,m.weight,m.price,m.conforming_p,m.nonconforming_p,m.scrap_one,b.manua_id as manual_id,b.goods_no,b.goods_name,b.source_no,b.goods_spec,b.current_type,b.unit1,b.source,b.goods_spec')->join('__BOOKS__ as b on m.books_id=b.id')->where(array('m.plan_id'=>$vs['id']))->select();
			foreach($arrival_goods as $k=>$v){
				$receive_amount=$v['weight'];//实收数量
				$conforming_p=$v['conforming_p'];//合格品数量
				$nonconforming_p=$v['nonconforming_p'];//残次品数量
				$scrap_one=$v['scrap_one'];//报废品数量
				//where唯一条件:商品编码相同，账册编码相同
				$where['goods_no']=$v['goods_no'];
				$where['manua_id']=$v['manual_id'];
				$res=$n->where($where)->find();
				
				if($res){//库存中已经有此商品，则更新库存数据
					$data_n['amount']=array('exp',"amount+$receive_amount");
					$data_n['conforming_p']=array('exp',"conforming_p+$conforming_p");
					$data_n['nonconforming_p']=array('exp',"nonconforming_p+$nonconforming_p");
					$data_n['scrap_one']=array('exp',"scrap_one+$scrap_one");
					//价格-平均价--总价/总数量
					$data_n['goods_price']=($res['goods_price']*$res['amount']+$v['receive_amount']*$v['price'])/($res['amount']+$v['receive_amount']);
					$ress=$n->where($where)->save($data_n);
					// echo $n->getlastsql();
					if($ress!==false){
						//更新批次详情
						$this->arrivalorderInfo($vs['purchasing_no'],$vs['batch_no'],$v);
						$mm->where(array("order_no"=>$vs['purchasing_no']))->setField('bar_code',$res['bar_code']);//更新条形码
						continue;
					}else{
						$this->error($v['goods_name'].'| 入库失败！');
					}
				}else{//库存中没有此商品,则添加此商品数据入库存
					$data['source_no']=$v['source_no'];
					$data['goods_name']=$v['goods_name'];
					$data['goods_no']=$v['goods_no'];
					$data['bar_code']=$v['bar_code'];
					$data['amount']=$receive_amount;
					$data['conforming_p']=$v['conforming_p'];
					$data['nonconforming_p']=$v['nonconforming_p'];
					$data['scrap_one']=$v['scrap_one'];
					$data['goods_price']=$v['price'];
					$data['goods_cate']=2;
					$data['manua_id']=$v['manual_id'];
					$data['goods_spec']=$v['goods_spec'];
					
					$resss=$n->add($data);
					// echo $n->getlastsql();
					// die;
					if($resss){
						//更新批次详情
						$this->arrivalorderInfo($vs['purchasing_no'],$vs['batch_no'],$v);
						
						continue;
					}else{
						$this->error($v['goods_name'].'| 入库失败！');
					}
				}
			}
			$s->where(array("id"=>$vs['id']))->setField('inbound_status',1);//更新入库状态
			
			// echo $s->getlastsql();
		}
		

        $return['info']='入库成功!';
        $return['status']=true;    
        $this->ajaxReturn($return);
    }
	//更新批次详情
    public function arrivalorderInfo($order_no,$batch_no,$arr=array()){
		 $n=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		 $v=$arr;
		 // dump($arr);
				$data_info_clild['order_no']=$order_no;
				$data_info_clild['batch_no']=$batch_no;
				$data_info_clild['plan_id']=$v['plan_id'];
				$data_info_clild['source_no']		=$v['source_no'];
				$data_info_clild['manual_id']		=$v['manual_id'];
				$data_info_clild['goods_spec']		=$v['goods_spec'];
				// $data_info_clild['item_no']			=$v['item_no'];
				// $data_info_clild['item_type']		=$v['item_type'];
				$data_info_clild['goods_no']		=$v['goods_no'];
				$data_info_clild['goods_name']		=$v['goods_name'];
				// $data_info_clild['declare_amount']	=$v['declare_amount'];
				$data_info_clild['receive_amount']	=$v['weight'];
				$data_info_clild['storage_amount']	=$data_info_clild['receive_amount'];
				// $data_info_clild['total_price']		=$v['total_price'];
				$data_info_clild['price']			=$v['price'];
				$data_info_clild['declare_unit']	=$v['unit1'];
				$data_info_clild['unit1']	=$v['unit1'];
				$data_info_clild['status']	=1;
				// $data_info_clild['inbound_status']	=1;
				
				$data_info_clild['country_code']	=$v['source'];
				$data_info_clild['currency']		=$v['current_type'];
				// $data_info_clild['bar_code']		=$v['bar_code'];
				// $data_info_clild['mark']			=$v['mark'];
				$data_info_clild['add_time']		=time();
				$data_info_clild['inbound_status']	=1;
				$data_info_clild['conforming_p']	=$v['conforming_p'];
				$data_info_clild['nonconforming_p']	=$v['nonconforming_p'];
				$data_info_clild['scrap_one']		=$v['scrap_one'];
				// $data_info_clild['scrap_two']		=$v['scrap_two'];
				$statuss=$n->add($data_info_clild);
				 // echo $n->getlastsql();
				 if(!$statuss){
					$res=$n->where(array('order_no'=>$order_no))->delete();//回滚操作
					$return['status']=0;
					$return['info']="商品编码[".$v['goods_no']."]添加失败";
					$this->ajaxReturn($return);
				 }
		 
	}
	//添加原料入库单
    public function purchasingorderAdd(){
		$m=M('PurchasingOrder',C('DB_PRS'),C('DB_DEPOT'));
        if(!IS_POST) exit; 
        $ck=A('CheckInput');
		$data['purchasing_no']=I('purchasing_no');
		$data['section_no']=I('section_no');
		$data['batch_no']=I('batch_no');
		$data['people_make_no']=I('people_make_no');
		$data['people_purchasing_no']=I('people_purchasing_no');
		$data['contacts_company_no']=I('contacts_company_no');
		$data['mark']=I('mark');
		
		$data['add_time']=time();
		
        $result=$m->add($data);
		// echo $m->getlastsql();
		// die;
        if(false===$result){
            $return['message']='添加失败';
            $return['status']=false;
            $this->ajaxReturn($return);
        }else{
            $return['message']='添加成功!';
			$return['status']=true; 
			$this->ajaxReturn($return);
        }
    }
	
	//删除
	public function purchasingorderDel(){
		$return=tableDel('PurchasingOrder');
        $this->ajaxReturn($return);
	}
	//清空
    public function purchasingorderClear(){
		$return=tableClear('PurchasingOrder');
        $this->ajaxReturn($return);
    }
	//恢复
    public function purchasingorderUndo(){
		$return=tableUndo('PurchasingOrder');
        $this->ajaxReturn($return);
    }
	//编辑原料入库单
    public function purchasingorderSave(){
		$m=M('PurchasingOrder',C('DB_PRS'),C('DB_DEPOT'));
        if(!IS_POST) exit; 
		$data['purchasing_no']=I('purchasing_no');
		$data['section_no']=I('section_no');
		$data['batch_no']=I('batch_no');
		$data['people_make_no']=I('people_make_no');
		$data['people_purchasing_no']=I('people_purchasing_no');
		$data['contacts_company_no']=I('contacts_company_no');
		$data['mark']=I('mark');
		
        $map['id']=I('id');
		
        $result=$m->where($map)->save($data);
		// echo $m->getlastsql();
        if(false===$result){
            $return['message']='更新到货信息失败';
            $return['status']=false;
            $this->ajaxReturn($return);
        }else{

			$return['message']='更新到货信息成功!';
			$return['status']=true; 
			$this->ajaxReturn($return);
        }
    }
	/**
	*监盘计划单打印
	**/
	public function print_plan(){
		$plan_id=I('id');
		$stat=M('ArrivalOrderPlan',C('DB_PRS'),C('DB_DEPOT'))->where('id="'.$plan_id.'"')->setField('plan_print_status',1);
		$url=U('printmonitordetail',array('id'=>$plan_id));

		if($stat!==false){
			$this->success($url);
		}else{
			$this->error('出错');
		}
	}
	/**
	*打印理货报告更改状态
	**/
	public function printtally() {

		$plan_receipts_id=I('plan_receipts_id');
		$id=I('id');
		$receive_no=I('receive_no');
		$data['receive_no']=$receive_no;
		$data['plan_id']=$id;
		$status=M('ArrivalOrderPlan',C('DB_PRS'),C('DB_DEPOT'))->where('order_no="'.$plan_receipts_id.'"')->setField('print_status',1);
		
		$this->success('更新打印状态成功,马上打印！');
		//实收数据接口
		// $pushapi = A('Pushapi'); 
		// $res=$pushapi->realsend();

		// if($res==2){
				// $this->error('计划入库但不存在');
		// }else if($res==1){
			// if($status!==false){
				// $stat=M('Tally')->where('plan_id='.$id)->find();
				// if($stat){
					// $this->success('更新打印状态成功,马上打印！');
				// }else{
					// if(M('Tally')->add($data)){
						// $this->success('更新打印状态成功,马上打印！');
					// }
				// }
			// }else{
				// $this->error('更新打印状态失败');
			// }
		// }else{
			// $this->error('推送数据失败');
		// }
	}
	//理货报告
	public function tally_iframe(){
		$id=I('id');//参数一
		$status=I('cid');//参数二
		$iframeUrl=U('tallyreport',array('id'=>$id,'status'=>$status));
		$this->assign('iframeUrl',$iframeUrl);
		$this->display('iframe');
	}
	//入库类型
	public function boundcatelist() {
		$m=M('BoundCate',C('DB_PRS'),C('DB_DEPOT'));
		$map['bound_cate_code']=1;//入库属性
		$list=$m->where($map)->select();
		return $list;
    }
	//理货报告-详情
	public function tallyreport(){
		$m=M('ArrivalOrderPlan',C('DB_PRS'),C('DB_DEPOT'));
		$n=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		$t=M('TallyReport',C('DB_PRS'),C('DB_DEPOT'));
		$id=I('id')?I('id'):0;
		$status=I('status');
		$boundcatelist=$this->boundcatelist();
		$this->assign('boundcatelist',$boundcatelist);
		
		if($id){
			// $ArrivalOrderPlan=M('ArrivalOrderPlan',C('DB_PRS'),C('DB_DEPOT'));
			$detail=$m->find($id);
			// if($detail['print_status']){
				$detail['report']=$t->where('plan_id='.$id)->find();
			// }
			// $ArrivalOrderPlansDetail=M('ArrivalOrderPlansDetail',C('DB_PRS'),C('DB_DEPOT'));
			$listrows=10;
				
			$p=I('p')?I('p'):1;
			$firstrow=($p-1)*$listrows;
			$count   = $n->where(array('order_no'=>$detail['order_no']))->count();// 查询满足要求的总记录数
			$Page    = new \Think\Page($count,$listrows);// 实例化分页类 传入总记录数和每页显示的记录数(25)
			$show    = $Page->show();// 分页显示输出
		
			
			$list=$n->where(array('order_no'=>$detail['order_no']))->select();
			
			$count_plan=0;
			$count_receive=0;
			// foreach($list as $k=>$v){
				// $list[$k]['merge']=M('MergeGoods')->where('goods_no="'.$v['goods_no'].'"')->find();
				// $count_plan=$count_plan+$v['declare_amount'];
				// $count_receive=$count_receive+$v['receive_amount'];
			// }
			// $this->assign("count_plan",$count_plan);
			// $this->assign("count_receive",$count_receive);
			$this->assign("list",$list);
			$this->assign("detail",$detail);
			$this->assign('page',$show);// 赋值分页输出
		}else{
			$this->error('请关联计划单id');
		}
		// dump($detail);
		$rows_max=9;//最大行数
		$rows_count=count($list);//列表行数
		$this->assign("rows_c",$rows_max-$rows_count);//剩余行数
		$this->assign("status",$status);//参数
		
		
		// dump($detail);
		if($status==1){
			$this->display('print_monitoring_one');
		}
		if($status==2){
			$this->display('print_monitoring_two');
		}
		if($status==3){
			$this->display('print_monitoring');
		}
		if($status==4){
			$this->display('print_monitoring');
		}
		
		
    }
	/**
	*修改差异原因
	**/
	public function editmonitoring(){
		date_default_timezone_set('PRC');
		$str=I('str');
		$n=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		$tr=M('TallyReport',C('DB_PRS'),C('DB_DEPOT'));
		if($str){				//批量修改
			$arr=explode(',',$str);
			// dump($arr);
			$datas=array();
			$plan_id=I('plan_id');
			$datas['delivery_numbers']=I('delivery_numbers');
			$datas['company']=I('company');
			$datas['year_top']=I('year_top');
			$datas['month_top']=I('month_top');
			$datas['no_top']=I('no_top');
			$datas['preentry_number']=I('preentry_number');
			$datas['year_arrival']=I('year_arrival');
			$datas['month_arrival']=I('month_arrival');
			$datas['day_arrival']=I('day_arrival');
			$datas['tally_time']=I('tally_time');
			$datas['tally']=I('tally');
			$datas['tally_check']=I('tally_check');
			$datas['plan_check']=I('plan_check');
			$datas['tally_address']=I('tally_address');
			$datas['tally_company']=I('tally_company');
			$datas['customs_broker']=I('customs_broker');
			$datas['total_difference']=I('total_difference');
			foreach($arr as $k=>$v){
				$arrs=explode(':',$v);
				$data=array();
				$data['mark']=$arrs[1];
				$data['conforming_p']=$arrs[2];
				$data['nonconforming_p']=$arrs[3];
				$data['scrap_one']=$arrs[4];
				$data['scrap_two']=$arrs[5];
				$data['receive_amount']=$arrs[6];
				$data['bar_code']=$arrs[7];
				$data['bound_cate_code']=$arrs[8];
				$data['overdue_time']=strtotime($arrs[9]);
				// $data['in_time']=time();
				$arrival_time="201".$datas['year_arrival']."-".$datas['month_arrival']."-".$datas['day_arrival'];
				// dump($arrival_time);
				// die;
				$data['arrival_time']=strtotime($arrival_time);
				
				$data['storage_amount']=$arrs[6];//库存数量
				if(substr($arrs[7],-1,6) != substr($arrs[0],-1,6)){
					// $this->error('输入的条形码与商品编码不匹配');
					alert_json(0,'输入的条形码与商品编码不匹配');
				}
				$res = $n->where('plan_id= '.$plan_id.'  and goods_no = "'.$arrs[0].'"')->save($data);
				// echo $n->getlastsql();
				// die;
				if($res !== false){
					continue;
				}else{
					// $this->error('更新出错');
					alert_json(0,'更新出错');
				}
			}
			
			
			$id=$tr->where('plan_id='.$plan_id)->find();
			
			if($id){
				$status=$tr->where('plan_id='.$plan_id)->save($datas);
				
			}else{
				$datas['create_time']=date('Y-m-d H:i:s');
				$datas['plan_id']=$plan_id;			   
				$status=$tr->add($datas);
			}
			if($status!==false){
				// $this->success('更新成功');
				alert_json(1,'更新成功');
			}else{
				// $this->error('更新出错');
				alert_json(0,'更新出错');
			}
		}else{								//单个修改
			// $this->error('无关联数据');
			alert_json(0,'无关联数据');
		}
	}
	/**
	*出库申报
	**/
	public function outboundReport(){
		$id=I('id');
		$m=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		$pushapi = A('Pushsendapi'); 
		$res=$pushapi->realsendCrossborderinbound();//入库申报状态
		
		if($res['flag']==1){
			$m->where(array('id'=>$id))->setField('plan_apply_status',1);
		}

		$this->ajaxReturn($res);
	}
	
	/**
	*实收申报
	**/
	public function outboundreceiveamountReport(){
		$id=I('id');
		$m=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		$pushapi = A('Pushsendapi'); 
		$res=$pushapi->realsendCrossborder();//实收申报状态
		
		if($res['flag']==1){
			$m->where(array('id'=>$id))->setField('receive_apply_status',1);
		}

		$this->ajaxReturn($res);
	}
	
	public function inboundPlan(){
		// C('URL_MODEL',0);
		$this->display();
    }
	public function booksCateInfo(){
		$BooksCate_list=M('BooksCate',C('DB_PRS'),C('DB_DEPOT'))->field('code')->where(array('status'=>1))->select();//账册列表

		$countrylist=countrylist();
		$coinlist=coinlist();
		$unitlist=unitlist();
		$manua_idlist=manua_idlist();//账册列表
		$this->assign('BooksCate_list',$BooksCate_list);
		$this->assign('manua_idlist',$manua_idlist);//产销国列表
		$this->assign('countrylist',$countrylist);//产销国列表
		$this->assign('coinlist',$coinlist);//币制列表
		$this->assign('unitlist',$unitlist);//单位列表
		$this->display();
    }

	public function confirm_arrival(){
		$storage_lists=storage_list();//库位列表
		$this->assign('storage_lists',json_encode($storage_lists));
		
		$this->display();
    }
	//删除
	public function purchasingordergoodsDel(){
		$return=tableDel('PurchasingOrderDetail');
        $this->ajaxReturn($return);
	}
	//清空
    public function purchasingordergoodsClear(){
		$return=tableClear('PurchasingOrderDetail');
        $this->ajaxReturn($return);
    }
	//恢复
    public function purchasingordergoodsUndo(){
		$return=tableUndo('PurchasingOrderDetail');
        $this->ajaxReturn($return);
    }
	//编辑
	public function purchasingordergoodsSave(){
		$m=M('PurchasingOrderDetail',C('DB_PRS'),C('DB_DEPOT'));
		$n=M('PurchasingOrder',C('DB_PRS'),C('DB_DEPOT'));
        if(!IS_POST) exit; 
		// dump(I());
		$weight=I('weight');
		$scrap_one=I('scrap_one');
		$nonconforming_p=I('nonconforming_p');
		$conforming_p=I('conforming_p');
		$price=I('price');
		$id=I('id');
        $map['id']=$id;
		$data['weight']=$weight;
		$data['price']=$price;
		$data['scrap_one']=$scrap_one;
		$data['nonconforming_p']=$nonconforming_p;
		$data['conforming_p']=$conforming_p;
		
		//检查是否已审核（审核后不能再添加）
		$detail_info=$m->find($id);
		$order_info=$n->where(array('id'=>$detail_info['plan_id']))->find();
		if($order_info['status']==1){
			$return['status']=0;
			$return['message']='已审核通过不能修改!';
			$this->ajaxReturn($return);
		}
        $result=$m->where($map)->save($data);
		// echo $m->getlastsql();
		// die;
        if(false===$result){
            $return['message']='更新信息失败';
            $return['status']=false;
            $this->ajaxReturn($return);
        }else{
            $return['message']='更新信息成功!';
			$return['status']=true; 
			$this->ajaxReturn($return);
        }
	}
	//添加详情
    public function purchastingorderaddgoods(){
		$m=M('PurchasingOrderDetail',C('DB_PRS'),C('DB_DEPOT'));
		$n=M('PurchasingOrder',C('DB_PRS'),C('DB_DEPOT'));
        if(!IS_POST) exit;
        $ck=A('CheckInput');
        $id=$ck->in('id','id','string','',1,0);
		$plan_id=$ck->in('订单id','plan_id','intval','',1,0);
		//检查是否已审核（审核后不能再添加）
		$order_info=$n->where(array('id'=>$plan_id))->find();
		if($order_info['status']==1){
			$return['status']=0;
			$return['message']='已通过审核不能再添加！';
			$this->ajaxReturn($return);
		}
        if(empty($id)) exit;//为空
		$data_n['add_goods']=1;
		$data_m['plan_id']=$plan_id;
		// $data_m['goods_cate']=2;
		$arr=explode(',', $id);
		$i=0;//新增
		$j=0;//失败
		$k=0;//重复
		foreach($arr as $key=>$v){
			$data_m['books_id']=$v;
			$detail=$m->where($data_m)->find();
			// echo $m->getlastsql();
			if($detail){
				$k++;
			}else{
				$result=$m->add($data_m);
				// echo $m->getlastsql();
				// die;
				if($result){
					$i++;
				}else{
					$j++;
				}
			}
		}
		if($i){
			$n->where(array('id'=>$plan_id))->save($data_n);
			$message=$i.'个添加成功!';
		}
		if($j){
			$message=$j.'个添加失败!';
		}
		if($k){
			$message=$k.'个重复!';
		}
		$return['message']=$message;
        $return['status']=true;
        $this->ajaxReturn($return);
	}
	
	//入库单详情列表
	public function get_purchasingorderInfo(){
		
		$m=M('PurchasingOrderDetail',C('DB_PRS'),C('DB_DEPOT'));
		$n=M('Books',C('DB_PRS'),C('DB_DEPOT'));
        $ck=A('CheckInput');
        //搜索条件
        $map=array();
		$map['m.plan_id']=I('id');
	
        $page=$ck->in('当前页','page','intval','1',0,0);   
        $rows=$ck->in('每页记录数','rows','intval','',0,0);  
		
        //排序
        $sort=$ck->in('排序','sort','cnennumstr','id',0,0);
        $order=$ck->in('规则','order','cnennumstr','desc',0,0);
		$status=I('status');
		if(empty($status)){
			$map['m.status']=array('neq',-1);
		}else{
			$map['m.status']=$status;
		}
        
        $count=$m->where($map)->count();
        $info=$m->alias('m')->field('m.id,m.weight,m.price,m.conforming_p,m.nonconforming_p,m.scrap_one,b.goods_no,b.goods_name,b.source_no,b.goods_spec,b.current_type,b.unit1,b.source,b.goods_spec')->join('__BOOKS__ as b on m.books_id=b.id')->where($map)->page($page,$rows)->order('b.'.$sort.' '.$order)->select();
// echo $m->getlastsql();
// die;
		foreach($info as $k=>$v){
			$info[$k]['add_time']=date('Y-m-d H:i:s',$v['add_time']);
			$info[$k]['examine_time']=date('Y-m-d H:i:s',$v['examine_time']);
		}
		
        if(!empty($info)){
            $data['total']=$count;
            $data['rows']=$info;
        }else{
            $data['total']=0;
            $data['rows']=0;
        }
        $this->ajaxReturn($data);
	}
	//账册详情列表
	public function get_books(){
		$m=M('Books',C('DB_PRS'),C('DB_DEPOT'));
		$coin=M('Coin',C('DB_PRS'),C('DB_DEPOT'));
		$country=M('Country',C('DB_PRS'),C('DB_DEPOT'));
		$unit=M('Unit',C('DB_PRS'),C('DB_DEPOT'));
        $ck=A('CheckInput');
        //搜索条件
        $map=array();
        $goods_no=$ck->in('商品编码','goods_no','ennumstr','',0,0);       
        !empty($goods_no)?$map['goods_no']=array('like','%'.$goods_no.'%'):'';
		$goods_name=$ck->in('商品名称','goods_name','cnennumstr','',0,0);       
        !empty($goods_name)?$map['goods_name']=array('like','%'.$goods_name.'%'):'';
		$bar_code=$ck->in('条形码','bar_code','ennumstr','',0,0);       
        !empty($bar_code)?$map['bar_code']=array('like','%'.$bar_code.'%'):'';
	
        $page=$ck->in('当前页','page','intval','1',0,0);   
        $rows=$ck->in('每页记录数','rows','intval','',0,0);  
		
        //排序
        $sort=$ck->in('排序','sort','cnennumstr','id',0,0);
        $order=$ck->in('规则','order','cnennumstr','desc',0,0);
		$status=I('status');
		if(empty($status)){
			$map['status']=array('neq',-1);
		}else{
			$map['status']=$status;
		}
        
        $count=$m->where($map)->count();
        if(empty($map)){
            $info=$m->page($page,$rows)->order($sort.' '.$order)->select();
        }else{
            $info=$m->where($map)->page($page,$rows)->order($sort.' '.$order)->select();
        }

		foreach($info as $k=>$v){
			$info_coin=$coin->where(array('coin_code'=>$v['current_type']))->find();
			$info_country=$country->where(array('country_code'=>$v['source']))->find();
			$info_uint1=$unit->where(array('unit_no'=>$v['unit1']))->find();
			$info_uint2=$unit->where(array('unit_no'=>$v['unit2']))->find();
			
			$info[$k]['current_type']=$info_coin['coin_name'];
			$info[$k]['source']=$info_country['country_name'];
			$info[$k]['unit1']=$info_uint1['unit_name'];
			$info[$k]['unit2']=$info_uint2['unit_name'];
			
			$info[$k]['add_time']=date('Y-m-d H:i:s',$v['add_time']);
			$info[$k]['examine_time']=date('Y-m-d H:i:s',$v['examine_time']);
		}
		
        if(!empty($info)){
            $data['total']=$count;
            $data['rows']=$info;
        }else{
            $data['total']=0;
            $data['rows']=0;
        }
        $this->ajaxReturn($data);
	}
	//生产计划单列表
	public function get_purchasingorder(){
		
		$m=M('PurchasingOrder',C('DB_PRS'),C('DB_DEPOT'));
		$n=M('PurchasingOrderDetail',C('DB_PRS'),C('DB_DEPOT'));
        $ck=A('CheckInput');
        //搜索条件
        $map=array();
        $purchasing_no=$ck->in('单号','purchasing_no','ennumstr','',0,0);       
        !empty($purchasing_no)?$map['purchasing_no']=array('like','%'.$purchasing_no.'%'):'';
	
        $page=$ck->in('当前页','page','intval','1',0,0);   
        $rows=$ck->in('每页记录数','rows','intval','',0,0);  
		
        //排序
        $sort=$ck->in('排序','sort','cnennumstr','id',0,0);
        $order=$ck->in('规则','order','cnennumstr','desc',0,0);
		$status=I('status');
		if(empty($status)){
			$map['status']=array('neq',-1);
		}else{
			$map['status']=$status;
		}
        
        $count=$m->where($map)->count();
        if(empty($map)){
            $info=$m->page($page,$rows)->order($sort.' '.$order)->select();
        }else{
            $info=$m->where($map)->page($page,$rows)->order($sort.' '.$order)->select();
        }

		foreach($info as $k=>$v){
			// $count_goods=$n->where(array('plan_id'=>$v['id']))->count();
			// if(!$count_goods){//没有详情信息
				// $info[$k]['add_time']=date('Y-m-d',$v['add_time']);
			// }
			$info[$k]['add_time']=date('Y-m-d H:i:s',$v['add_time']);
			$info[$k]['examine_time']=date('Y-m-d H:i:s',$v['examine_time']);
			
			if(!$v['status']){
				$info[$k]['color']=0;
			}
		}
		
        if(!empty($info)){
            $data['total']=$count;
            $data['rows']=$info;
        }else{
            $data['total']=0;
            $data['rows']=0;
        }
        $this->ajaxReturn($data);
	}
	//入库单-详情
	public function get_arrivalorder(){
		$m=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		$n=M('ArrivalOrderPlan',C('DB_PRS'),C('DB_DEPOT'));
        $ck=A('CheckInput');
		//参数验证
        $id=I('id');
		$status=I('status');
		//导出Excel
		$excel=I('excel');
		//排序
        $sort=$ck->in('排序','sort','cnennumstr','id',0,0);
        $order=$ck->in('规则','order','cnennumstr','desc',0,0);
		//搜索条件
		$map=array();
		$info=$n->where(array('id'=>$id))->find();
		$map['order_no']=$info['order_no'];
		
		//获取数据
        // $data=getTable('ArrivalOrder',$map,$page,$rows,$sort,$order,$status);
		$data['rows']=$m->where($map)->order($sort.' '.$order)->select();
		$data['total']=$m->where($map)->count();
		// dump($data);
		foreach($data['rows'] as $k=>$v){
			$data['rows'][$k]['expected_time']=date('Y-m-d H:i:s',$v['expected_time']);
			if(!empty($excel)){ //导出Excel
				$data['rows'][$k]['source_no']=' '.$v['source_no'];
				$data['rows'][$k]['bar_code']=' '.$v['bar_code'];
				$data['rows'][$k]['all_count_nums']=$v['conforming_p']+$v['nonconforming_p']+$v['scrap_one']+$v['scrap_two'];//合计
				$ssss=$v['declare_amount']-$data['rows'][$k]['all_count_nums'];
				if($ssss>0){
					$data['rows'][$k]['d_count']='';//多到货
					$data['rows'][$k]['s_count']=$ssss;//少到货
				}else if($ssss==0){
					$data['rows'][$k]['d_count']='';//多到货
					$data['rows'][$k]['s_count']='';//少到货
				}else{
					$data['rows'][$k]['d_count']=abs($ssss);//多到货
					$data['rows'][$k]['s_count']='';//少到货
				}
			}
		}
		if(!empty($excel)){ //导出Excel
			$xlsName  = "仓储/电商公司：杭州天众供应链管理有限公司                   杭州跨境贸易电子商务产业园(下沙）保税仓理货报告   2017年__月总第___号";
			$xlsCell  = array(
				array('item_no','项号'),
				array('goods_name','中文品名'),
				array('source_no','料号'),
				array('bar_code','条形码'),
				array('declare_amount','理论入库数据'),
				array('unit1','单位'),
				array('conforming_p','合格品'),
				array('nonconforming_p','残次品'),
				array('scrap_one','报废品1'),
				array('scrap_two','报废品2'),
				array('all_count_nums','合计'),
				array('d_count','多到货'),
				array('s_count','少到货'),
				array('mark','差异原因')
			);
			$this->inboundPlan_exportExcel($xlsName,$xlsCell,$data['rows']);
			die;
		}
        $this->ajaxReturn($data);
    }
	//导出理货报告excel
	public function inboundPlan_exportExcel($expTitle,$expCellName,$expTableData){
			$xlsTitle = '理货报告';//文件名称
			$fileName = $xlsTitle.date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
			$cellNum = count($expCellName);
			$dataNum = count($expTableData);
			//vendor("PHPExcel.PHPExcel");
		   
			//导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
			import("Org.Util.PHPExcel");
			import("Org.Util.PHPExcel.Writer.Excel5");
			import("Org.Util.PHPExcel.IOFactory.php");
		   
		    $date = date("Y_m_d",time());
			$fileName .= "_{$date}.xls";

			//创建PHPExcel对象，注意，不能少了\
			$objPHPExcel = new \PHPExcel();
			//$objProps = $objPHPExcel->getProperties();
			
			//$objPHPExcel = new PHPExcel();
			$cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
			//表头-begin
			//合并单元格-begin
			$objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum].'1');
			$objPHPExcel->getActiveSheet(0)->mergeCells('A2:B3');
			$objPHPExcel->getActiveSheet(0)->mergeCells('C2:F3');
			$objPHPExcel->getActiveSheet(0)->mergeCells('G2:M3');
			$objPHPExcel->getActiveSheet(0)->mergeCells('N2:O2');
			$objPHPExcel->getActiveSheet(0)->mergeCells('N3:O3');
			
			$objPHPExcel->getActiveSheet(0)->mergeCells('A4:A5');
			$objPHPExcel->getActiveSheet(0)->mergeCells('B4:B5');
			$objPHPExcel->getActiveSheet(0)->mergeCells('C4:C5');
			$objPHPExcel->getActiveSheet(0)->mergeCells('D4:D5');
			$objPHPExcel->getActiveSheet(0)->mergeCells('E4:E5');
			$objPHPExcel->getActiveSheet(0)->mergeCells('F4:F5');
			$objPHPExcel->getActiveSheet(0)->mergeCells('G4:K4');
			$objPHPExcel->getActiveSheet(0)->mergeCells('I5:J5');
			$objPHPExcel->getActiveSheet(0)->mergeCells('L4:M4');
			$objPHPExcel->getActiveSheet(0)->mergeCells('N4:O5');
			//自动换行
			$objPHPExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setWrapText(true);
			
			//居中-begin
			$objPHPExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);//垂直居中
			$objPHPExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//水平居中
			$objPHPExcel->getActiveSheet(0)->getStyle('B')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);//左对齐
			//设置字体大小-begin
			$objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(10);
			$objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setName('Arial');
			$objPHPExcel->getActiveSheet()->getStyle('A1:O3')->getFont()->setName('宋体');
			$objPHPExcel->getActiveSheet()->getStyle('A1:O3')->getFont()->setSize(9);
			$objPHPExcel->getActiveSheet()->getStyle('A3:O5')->getFont()->setSize(11);
			
			//设置粗体-begin
			$objPHPExcel->getActiveSheet()->getStyle('A1:O5')->getFont()->setBold(true);
			//设置单元格宽度-begin
			$objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(9);
			$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(22);
			$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
			$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
			//设置标题-begin
		    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1',$expTitle);
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A2','转关单号(入库单号）：');  
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('C2','提运单号：S00000000                            核放单编号： ZK0000000000000000000000');  
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('G2','商家（账册号）：W29916000086');  
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('N2','预录入号：');  
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('G4','实际入库数量');
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('L4','差异数量');  
			
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A4','项号');  
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('B4','中文品名');  
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('C4','料号');  
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('D4','条形码');  
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('E4','理论入库数据');  
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('F4','单位');  
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('G5','合格品');  
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('H5','残次品');  
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('I5','报废品');  
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('K5','合计');  
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('L5','多到货');  
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('M5','少到货');
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('N4','差异原因');  
			//设置标题-end

			// Miscellaneous glyphs, UTF-8   
			$declare_amount_count=0;
			$receive_amount_count=0;
			$all_count=0;
			
			for($i=0;$i<$dataNum;$i++){
			  for($j=0;$j<$cellNum;$j++){
				$objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+6), $expTableData[$i][$expCellName[$j][0]]);
				$objPHPExcel->getActiveSheet(0)->getStyle('B'.($i+6))->getAlignment()->setWrapText(false);
			  }
			  $objPHPExcel->getActiveSheet(0)->mergeCells('N'.($i+6).':'.'O'.($i+6));
			  $declare_amount_count+=$expTableData[$i][$expCellName[4][0]];
			  $receive_amount_count+=$expTableData[$i][$expCellName[6][0]];
			  $all_count+=$expTableData[$i][$expCellName[10][0]];
			}
			$objPHPExcel->getActiveSheet(0)->mergeCells('N'.(6+$dataNum).':'.'O'.(6+$dataNum));
			$objPHPExcel->getActiveSheet(0)->mergeCells('N'.(7+$dataNum).':'.'O'.(7+$dataNum));
			//设置页脚-begin
			for($j=0;$j<$cellNum-3;$j++){
				$objPHPExcel->getActiveSheet(0)->mergeCells($cellName[$j].(6+$dataNum).':'.$cellName[$j].(7+$dataNum));
			}
			$objPHPExcel->getActiveSheet(0)->mergeCells('L'.(7+$dataNum).':'.'M'.(7+$dataNum));
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.(6+$dataNum),'合计');
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('L'.(7+$dataNum),'差异合计：');
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.(6+$dataNum),$declare_amount_count);
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.(6+$dataNum),$receive_amount_count);
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('K'.(6+$dataNum),$all_count);
			
			$objPHPExcel->getActiveSheet(0)->mergeCells('B'.(8+$dataNum).':'.'O'.(8+$dataNum));
			$objPHPExcel->getActiveSheet(0)->mergeCells('A'.(9+$dataNum).':'.'M'.(9+$dataNum));
			$objPHPExcel->getActiveSheet(0)->mergeCells('A'.(10+$dataNum).':'.'M'.(10+$dataNum));
			$objPHPExcel->getActiveSheet(0)->mergeCells('N'.(9+$dataNum).':'.'O'.(10+$dataNum));
			$objPHPExcel->getActiveSheet(0)->mergeCells('A'.(11+$dataNum).':'.'O'.(11+$dataNum));
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.(8+$dataNum),'备注：');
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.(8+$dataNum),'数据单位：以向海关申报单位为准。');
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.(9+$dataNum),'理货时间(日期）：'.date('Y年m月d日',time()).'    理货：             理货审核：                监盘审核: ');
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.(10+$dataNum),'理货地址：钱城国际7-3D                                       理货公司：杭州天众供应链管理有限公司');
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.(11+$dataNum),'      本报告以打印版本为准，手写（或涂改）无效。  ');
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue('N'.(9+$dataNum),'报关公司：杭州桥宇国际货运代理有限公司');
			
			$objPHPExcel->getActiveSheet()->getStyle('A'.(8+$dataNum).':'.'O'.(11+$dataNum))->getFont()->setName('宋体');
			$objPHPExcel->getActiveSheet()->getStyle('A'.(8+$dataNum))->getFont()->setSize(9);
			$objPHPExcel->getActiveSheet()->getStyle('A'.(9+$dataNum).':'.'O'.(11+$dataNum))->getFont()->setSize(11);
			
			//设置粗体-begin
			$objPHPExcel->getActiveSheet()->getStyle('A'.(8+$dataNum).':'.'O'.(10+$dataNum))->getFont()->setBold(true);
			//设置页脚-end
			
			for($i=0;$i<$dataNum+11;$i++){
			  for($j=0;$j<$cellNum+1;$j++){
				//设置边框颜色
				$objPHPExcel->getActiveSheet()->getStyle($cellName[$j].$i)->getBorders()->getTop()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
				$objPHPExcel->getActiveSheet()->getStyle($cellName[$j].$i)->getBorders()->getBottom()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
				$objPHPExcel->getActiveSheet()->getStyle($cellName[$j].$i)->getBorders()->getLeft()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
				$objPHPExcel->getActiveSheet()->getStyle($cellName[$j].$i)->getBorders()->getRight()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
				$objPHPExcel->getActiveSheet()->getStyle($cellName[$j].$i)->getBorders()->getTop()->getColor()->setARGB('000000');
				$objPHPExcel->getActiveSheet()->getStyle($cellName[$j].$i)->getBorders()->getBottom()->getColor()->setARGB('000000');
				$objPHPExcel->getActiveSheet()->getStyle($cellName[$j].$i)->getBorders()->getLeft()->getColor()->setARGB('000000');
				$objPHPExcel->getActiveSheet()->getStyle($cellName[$j].$i)->getBorders()->getRight()->getColor()->setARGB('000000');
			  }
			}

			header('pragma:public');
			header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
			header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
			$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  
			$objWriter->save('php://output'); 
			exit;   
	}
	//入库单
	public function get_inboundPlan(){
        $ck=A('CheckInput');
		//参数验证
        $order_no=$ck->in('单号','order_no','ennumstr','',0,0);
		$status=I('status');
		$page=$ck->in('当前页','page','intval','1',0,0);
        $rows=$ck->in('每页记录数','rows','intval','',0,0);
		//排序
        $sort=$ck->in('排序','sort','cnennumstr','id',0,0);
        $order=$ck->in('规则','order','cnennumstr','desc',0,0);
		//搜索条件
		$map=array();
		!empty($order_no)?$map['order_no']=array('like','%'.$order_no.'%'):'';
		
		//获取数据
        $data=getTable('ArrivalOrderPlan',$map,$page,$rows,$sort,$order,$status);
		// dump($data);
		foreach($data['rows'] as $k=>$v){
			$data['rows'][$k]['expected_time']=date('Y-m-d H:i:s',$v['expected_time']);
		}
        $this->ajaxReturn($data);
    }
	
	//审核原料入库单
    public function examinepurchasingorder(){
		$mm=M('PurchasingOrder',C('DB_PRS'),C('DB_DEPOT'));
		$mmd=M('PurchasingOrderDetail',C('DB_PRS'),C('DB_DEPOT'));
		$id=I('id');
		$value=I('value');
        if(empty($id)) exit;//为空
		$arr=explode(',', $id);
		
		foreach($arr as $keys=>$values){
			$order_info=$mm->where(array('id'=>$values))->find();
			$count=$mmd->where(array('plan_id'=>$values))->count();//原料数量
			if(!$count){
				$return['status']=0;
				$return['message']='单号:'.$order_info['purchasing_no'].'，未添加原料不能审核！';
				$this->ajaxReturn($return);
				die;
			}
		}
		
		$return=tableExamine('PurchasingOrder');
        $this->ajaxReturn($return);
    }
	//审核入库单
    public function examineinboundPlan(){
		$return=tableExamine('ArrivalOrderPlan');
        $this->ajaxReturn($return);
    }
	//过期时间快捷查询
	public function get_overduefast(){
		
        $m=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
        $ck=A('CheckInput');
		$goodsId=I('goodsId');
        //搜索条件
        $map=array();
		$week=I('week');//周数
		$monthx=I('monthx');//开始的月数
		$monthy=I('monthy');//结束的月数
		if(!empty($week)){
			$times_w=$week*7*86400;//几周的秒数
			$start_time=time();
			$end_time=time()+$times_w;
		}else{
			if(!empty($monthx)){
				$time_m_x=$monthx*30*86400;//几月的秒数
			}
			if(!empty($monthy)){
				$time_m_y=$monthy*30*86400;//几月的秒数
			}
			$start_time=time()+$time_m_x;
			$end_time=time()+$time_m_y;
		}
		$map['_string'] = "overdue_time>=$start_time AND overdue_time<=$end_time";		
		$map['status']=1;//审核通过
		$map['inbound_status']=1;//已入库
		$map['grounding_status']=1;//已上架
		
        $page=$ck->in('当前页','page','intval','1',0,0);   
        $rows=$ck->in('每页记录数','rows','intval','',0,0);  

        //排序
        $sort=$ck->in('排序','sort','cnennumstr','id',0,0);
        $order=$ck->in('规则','order','cnennumstr','desc',0,0);
        
        $count=$m->where($map)->count();
        if(empty($map)){
            $info=$m->page($page,$rows)->order($sort.' '.$order)->select();
        }else{
            $info=$m->where($map)->order($sort.' '.$order)->select();
        }
		// echo $m->getlastsql();
		foreach($info as $k=>$v){
			$info[$k]['expected_time']=date("Y-m-d H:i:s",$v['expected_time']);
			$info[$k]['arrival_time']=date("Y-m-d H:i:s",$v['arrival_time']);
			$info[$k]['examine_time']=date("Y-m-d H:i:s",$v['examine_time']);
			$info[$k]['overdue_time']=date("Y-m-d H:i:s",$v['overdue_time']);
			$info[$k]['add_time']=date("Y-m-d H:i:s",$v['add_time']);
			$info[$k]['push_arrival_time']=date("Y-m-d H:i:s",$v['push_arrival_time']);
			$info[$k]['push_grounding_time']=date("Y-m-d H:i:s",$v['push_grounding_time']);
			$s=M('Storage',C('DB_PRS'),C('DB_DEPOT'));
			$storage_info=$s->where(array('storage_code'=>$v['storage_code']))->find();
			$info[$k]['storage_code']=$storage_info['name'];
			if($v['status']==0){
				$info[$k]['status']="未审核";
				$info[$k]['color']=0;//设定颜色
			}
			
			
			if($v['status']==1){
				$info[$k]['status']="已通过";
			}
			if($v['status']==2){
				$info[$k]['status']="未通过";
			}
			if($v['inbound_status']==0){
				$info[$k]['inbound_status']="否";
			}
			if($v['inbound_status']==1){
				$info[$k]['inbound_status']="是";
			}
			if($v['cloud_depot_status']==0){
				$info[$k]['cloud_depot_status']="否";
			}
			if($v['cloud_depot_status']==1){
				$info[$k]['cloud_depot_status']="是";
			}

			$unit=M('Unit',C('DB_PRS'),C('DB_DEPOT'));
			$unit_info=$unit->where(array('unit_no'=>$v['cloud_unit']))->find();
			$info[$k]['cloud_unit']=$unit_info['unit_name'];
		}
        if(!empty($info)){
            $data['total']=$count;
            $data['rows']=$info;
        }else{
            $data['total']=0;
            $data['rows']=0;
        }
        $this->ajaxReturn($data);
    }
	//入库明细
	public function get_arrivallog(){

		$ao=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		$param=I('param.','','trim');
		$map=array();
		
		if(empty($param['start_time'])){
			$start_time=strtotime(0);
		}else{
			$start_time=strtotime($param['start_time']);
		}
		if(empty($param['end_time'])){
			$end_time=time();
		}else{
			$end_time=strtotime($param['end_time']);
		}
		if(!empty($param['order_no'])){
			$order_no=$param['order_no'];
			$map['order_no']=array('like',"$order_no");
		}
		if(!empty($param['goods_no'])){
			$goods_no=$param['goods_no'];
			$map['goods_no']=array('like',"$goods_no");
		}

		$map['arrival_time']=array(array('gt',$start_time),array('lt',$end_time));
		//导出Excel
		$excel=I('excel');
		
		$page=empty($param['page'])?'1':$param['page'];
        $rows=empty($param['rows'])?'15':$param['rows'];
        //排序
        $sort=empty($param['sort'])?'id':$param['sort'];
        $order=empty($param['order'])?'desc':$param['order'];
		
		if(!empty($excel)){ //导出Excel
			$list=$ao->where($map)->order('id desc')->select();
		}else{
			$list=$ao->where($map)->page($page,$rows)->order($sort.' '.$order)->select();
		}
		$count=$ao->where($map)->count();
		foreach($list as $k=>$v){
			$list[$k]['arrival_time']=date('Y-m-d H:i:s',$v['arrival_time']);
		}
		
		if(!empty($excel)){ //导出Excel
			$xlsName  = "入库明细";
			$xlsCell  = array(
				array('order_no','单号'),
				array('batch_no','批次号'),
				array('goods_no','商品编码'),
				array('goods_name','商品名称'),
				array('price','单价'),
				array('receive_amount','实收数量'),
				array('arrival_time','入库时间')
			);
			exportExcel($xlsName,$xlsCell,$list);
			die;
		}
		
		if(!empty($list)){
            $data['total']=$count;
            $data['rows']=$list;
        }else{
            $data['total']=0;
            $data['rows']=0;
        }
        $this->ajaxReturn($data);
	}
	//到货通知单列表
	public function get_arrival(){
        $m=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
        $ck=A('CheckInput');
		$goodsId=I('goodsId');
        //搜索条件
        $map=array();
		$param=I('param.','','trim');
        $order_no=$param['order_no'];
		$manual_id=$param['manual_id'];
        $goods_no=$param['goods_no'];
		$goods_name=$param['goods_name'];
		$inbound_status=$param['inbound_status'];
		$cloud_depot_status=$param['cloud_depot_status'];
		$grounding_status=$param['grounding_status'];
		$start_time=$param['start_time'];
		$end_time=$param['end_time'];
		$time_cate=$param['time_cate'];
		$search_storage_code=$param['search_storage_code'];
		
        !empty($order_no)?$map['order_no']=array('like','%'.$order_no.'%'):'';
		!empty($manual_id)?$map['manual_id']=array('like','%'.$manual_id.'%'):'';
		!empty($goods_no)?$map['goods_no']=array('like','%'.$goods_no.'%'):'';
		!empty($goods_name)?$map['goods_name']=array('like','%'.$goods_name.'%'):'';
		if(!empty($goodsId)){
			$goods=M('Goods',C('DB_PRS'),C('DB_DEPOT'))->find($goodsId);
			$map['goods_no']=$goods['goods_no'];
		}
		
		if(!empty($search_storage_code)){
			$map['storage_code']=$search_storage_code;
		}
		
		if($grounding_status==='1'){//已上架
			$map['grounding_status']=1;
		}
		
		if($grounding_status==='0'){
			$map['grounding_status']=0;
		}

		if($inbound_status==='1'){//已入库
			$map['inbound_status']=1;
		}
		if($inbound_status==='0'){//未入库
			$map['inbound_status']=0;
		}

		if($cloud_depot_status==='1'){//是云仓商品
			$map['cloud_depot_status']=1;
		}
		if($cloud_depot_status==='2'){
			$map['cloud_depot_status']=0;
		}

		!empty($start_time)?$start_time = strtotime($start_time):$start_time=0;
		!empty($end_time)?$end_time = strtotime($end_time):$end_time =time();
		
		if($time_cate==1){//到货时间
			$map['_string'] = "arrival_time>=$start_time AND arrival_time<=$end_time";		
		}
		if($time_cate==2){//预计到货时间
			$map['_string'] = "expected_time>=$start_time AND expected_time<=$end_time";		
		}
		if($time_cate==3){//审核时间
			$map['_string'] = "examine_time>=$start_time AND examine_time<=$end_time";		
		}
		if($time_cate==4){//推送实收时间
			$map['_string'] = "push_arrival_time>=$start_time AND push_arrival_time<=$end_time";
		}
		if($time_cate==5){//数据接收时间
			$map['_string'] = "add_time>=$start_time AND add_time<=$end_time";		
		}
		if($time_cate==6){//过期时间
			$map['_string'] = "overdue_time>=$start_time AND overdue_time<=$end_time";		
		}
		$status=I('status');//确认到货参数
		if($status<>3){
			if($status){
				$map['status']=array('neq',0);
			}else{
				$map['status']=0;
			}
		}
        $page=$ck->in('当前页','page','intval','1',0,0);   
        $rows=$ck->in('每页记录数','rows','intval','',0,0);  
        //排序
        $sort=$ck->in('排序','sort','cnennumstr','id',0,0);
        $order=$ck->in('规则','order','cnennumstr','desc',0,0);
        
        $count=$m->where($map)->count();
		//导出Excel
        $excel=I('excel');

        if(empty($map)){
            if(!empty($excel)) { //导出Excel
                $info=$m->order($sort.' '.$order)->select();
            }else{
                $info=$m->page($page,$rows)->order($sort.' '.$order)->select();
            }

        }else{
            if(!empty($excel)) { //导出Excel
                $info=$m->where($map)->order($sort.' '.$order)->select();
            }else{
                $info=$m->where($map)->page($page,$rows)->order($sort.' '.$order)->select();
            }

        }
		//dump($param);
		//echo $m->getlastsql();
		//die;
		foreach($info as $k=>$v){
			$info[$k]['expected_time']=date("Y-m-d H:i:s",$v['expected_time']);
			$info[$k]['arrival_time']=date("Y-m-d H:i:s",$v['arrival_time']);
			$info[$k]['t_arrival_time']=date("Y-m-d H:i:s",$v['t_arrival_time']);
			$info[$k]['examine_time']=date("Y-m-d H:i:s",$v['examine_time']);
			$info[$k]['overdue_time']=date("Y-m-d H:i:s",$v['overdue_time']);
			$info[$k]['bar_code']=' '.$v['bar_code'];
			$guoqitime=timediff(time(),$v['overdue_time']);
			if(time()>$v['overdue_time']){
				$info[$k]['overdue_time_str']="已过期";
				$info[$k]['color']=0;//设定颜色
			}else{
				if($guoqitime['day']){
					$info[$k]['overdue_time_str']='还差'.$guoqitime['day'].'天';
				}else{
					$info[$k]['overdue_time_str']='还差'.$guoqitime['hour'].'小时'.$guoqitime['min'].'分';
				}
			}
			$info[$k]['add_time']=date("Y-m-d H:i:s",$v['add_time']);
			$info[$k]['push_arrival_time']=date("Y-m-d H:i:s",$v['push_arrival_time']);
			$info[$k]['push_grounding_time']=date("Y-m-d H:i:s",$v['push_grounding_time']);
			$s=M('Storage',C('DB_PRS'),C('DB_DEPOT'));
			$storage_info=$s->where(array('storage_code'=>$v['storage_code']))->find();
			// echo $s->getlastsql();
			// die;
			$info[$k]['storage_code']=$storage_info['name'];//获得当前库位名
			if($v['status']==0){
				$info[$k]['status']="未审核";
				$info[$k]['color']=0;//设定颜色
			}
			if($v['confirm_status']==0){
				$info[$k]['color']=0;//设定颜色
			}
			if($v['status']==1){
				$info[$k]['status']="已通过";
			}
			if($v['status']==2){
				$info[$k]['status']="未通过";
			}
			if($v['inbound_status']==0){
				$info[$k]['inbound_status']="否";
			}
			if($v['inbound_status']==1){
				$info[$k]['inbound_status']="是";
			}
			if($v['cloud_depot_status']==0){
				$info[$k]['cloud_depot_status']="否";
			}
			if($v['cloud_depot_status']==1){
				$info[$k]['cloud_depot_status']="是";
			}
			$unit=M('Unit',C('DB_PRS'),C('DB_DEPOT'));
			$unit_info=$unit->where(array('unit_no'=>$v['cloud_unit']))->find();
			$info[$k]['cloud_unit']=$unit_info['unit_name'];
		}
		if(!empty($excel)){ //导出Excel
            $xlsName  = "商品上架";
            $xlsCell  = array(
                array('order_no','单号'),
                array('manual_id','账册编号'),
                array('goods_no','商品编码'),
                array('goods_name','商品名称'),
                array('price','单价'),
                array('receive_amount','实收数量'),
                array('storage_amount','库存数量'),
                array('freez_amount','冻结数量'),
                array('bar_code','条形码'),
                array('storage_code','库位'),
                array('area','面积'),
                array('overdue_time','过期时间'),
                array('overdue_time_str','过期剩余天数'),
                array('conforming_p','合格品'),
                array('nonconforming_p','残次品'),
                array('scrap_one','报废品'),
                array('arrival_time','到货时间')
            );
            exportExcel($xlsName,$xlsCell,$info);
            die;
        }
        if(!empty($info)){
            $data['total']=$count;
            $data['rows']=$info;
        }else{
            $data['total']=0;
            $data['rows']=0;
        }
        $this->ajaxReturn($data);
    }
	//审核到货通知单
    public function get_examine(){
		$m=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
        if(!IS_POST) exit;
        $ck=A('CheckInput');  
        $id=$ck->in('到货通知单id','id','string','',1,0);
		$value=$ck->in('审核状态参数','value','intval','',1,1);
        if(empty($id)) exit;//为空
        $arr=explode(',', $id);
        $map['id']=array('in',$arr);
		if($value==1){
			$data['status']=1;
		}else if($value==2){
			$data['status']=2;
		}else{
			$return['message']='审核状态参数错误!';
            $return['status']=false;
			$this->ajaxReturn($return);
			exit;
		}
		$data['examine_time']=time();
        $result=$m->where($map)->save($data);
        if(!$result){
            $return['message']='审核失败!';
            $return['status']=false;  
        }else{
				//推送审核结果
				$order_list=$m->field('old_goods_id,status,erp_code')->where($map)->select();
				// dump(json_encode($order_list));
				$url=C('BASE_CONFIG.examine_arrival');//推送审核结果接口
				
				$push=A('Pushsendapi');
				$res = $push->push($url,$order_list);
				// dump($res);
				// die;
				$status=json_decode($res,true);
				if(!empty($status)){
					$i=0;
					if($status['flag']){
						foreach($status['data'] as $k=>$v){
							$maps['old_goods_id']=$k;
							foreach($v as $key=>$value){
								if($value['is_true']==1){
									$i++;
								}
							}
						}
					}
					// $return['status']=1;
					// $return['info']=$i.'条推送成功！';
					// dump($return);
					// $this->ajaxReturn($return);
				}else{
					$return['status']=0;
					$return['info']='推送失败！';
					$this->ajaxReturn($return);
				}
             $return['message']='审核成功!';
             $return['status']=true; 
        }
        $this->ajaxReturn($return);
    }
	//更新实收数据
    public function confirmArrivalSave(){
		
		$m=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
        if(!IS_POST) exit; 
        $ck=A('CheckInput');
        $data['receive_amount']=$ck->in('实际到货数量','receive_amount','intval','',1,10);
		$data['price']=$ck->in('单价','price','float','',1,20);
		$data['conforming_p']=$ck->in('合格品数量','conforming_p','intval','',1,10);
		$data['nonconforming_p']=$ck->in('残次品数量','nonconforming_p','intval','',1,10);
		$data['scrap_one']=$ck->in('报废品数量','scrap_one','intval','',1,10);
		$data['update_time']=time();
		// $data['arrival_time']=time();
		$data['storage_amount']=$data['receive_amount'];//库存数量
		
		$data['status']=1;//华艋需求
        $map['id']=$ck->in('erp企业id','id','intval','',1,0);
		
		if(!$data['conforming_p']){
			$return['message']='合格品数量不能为0';
            $return['status']=false;
            $this->ajaxReturn($return);
		}
        $result=$m->where($map)->save($data);
		
        if(false===$result){
            $return['message']='更新到货信息失败';
            $return['status']=false;
            $this->ajaxReturn($return);
        }else{

			$return['message']='更新到货信息成功!';
			$return['status']=true; 
			$this->ajaxReturn($return);
        }
    }
	//实收入库
    public function arrival_inbound(){
		$trans = M('',C('DB_PRS'),C('DB_DEPOT'));
		$trans->startTrans();   // 开启事务
		$m=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		$n=M('Goods',C('DB_PRS'),C('DB_DEPOT'));
        if(!IS_POST) exit;
        $ck=A('CheckInput');
		$id=$ck->in('到货通知单id','id','string','',1,0);
        if(empty($id)) exit;//为空
        $arr=explode(',', $id);
		$map['id']=array('in',$arr);
		$arrival_goods=$m->where($map)->select();
		
		foreach($arrival_goods as $k=>$v){
			if($v['inbound_status']==1){
				continue;//已经入库，则继续循环
			}
			$receive_amount=$v['receive_amount'];//实收数量
			$conforming_p=$v['conforming_p'];//合格品数量
			$nonconforming_p=$v['nonconforming_p'];//残次品数量
			$scrap_one=$v['scrap_one'];//报废品数量
			//where唯一条件:商品编码相同，账册编码相同
			$where['goods_no']=$v['goods_no'];
			$where['manua_id']=$v['manual_id'];
			
			$res=$n->where($where)->find();
			if(!empty($res)){//库存中已经有此商品，则更新库存数据
				$data_n['amount']=array('exp',"amount+$receive_amount");//总数量
				
				$data_n['conforming_p']=array('exp',"conforming_p+$conforming_p");
				$data_n['nonconforming_p']=array('exp',"nonconforming_p+$nonconforming_p");
				$data_n['scrap_one']=array('exp',"scrap_one+$scrap_one");
				//价格(平均价)=总价/总数量
				$data_n['goods_price']=($res['goods_price']*$res['amount']+$v['receive_amount']*$v['price'])/($res['amount']+$v['receive_amount']);
					
				$ress=$n->where($where)->save($data_n);

				if($ress!==false){
					$m->where(array("id"=>$v['id']))->setField('inbound_status',1);//更新入库状态
					$m->where(array("id"=>$v['id']))->setField('bar_code',$res['bar_code']);//更新条形码
					continue;
				}else{
					$trans->rollback();
					$this->error($v['goods_name'].'| 入库失败！');
				}
			}else{//库存中没有此商品,则添加此商品数据入库存
				$data['source_no']=$v['source_no'];
				$data['goods_name']=$v['goods_name'];
				$data['goods_no']=$v['goods_no'];
				$data['bar_code']=$v['bar_code'];
				$data['amount']=$receive_amount;
				$data['conforming_p']=$v['conforming_p'];
				$data['nonconforming_p']=$v['nonconforming_p'];
				$data['scrap_one']=$v['scrap_one'];
				$data['goods_price']=$v['price'];
				if(!empty($v['current_type'])){
					$data['current_type']=$v['current_type'];
				}
				$data['manua_id']=$v['manual_id'];
				$data['goods_spec']=$v['goods_spec'];
				$data['unit1']=$v['unit1'];
				$data['unit2']=$v['unit2'];
				
				$resss=$n->add($data);

				if($resss){
					$m->where(array("id"=>$v['id']))->setField('inbound_status',1);//更新入库状态
					continue;
				}else{
					$trans->rollback();
					$this->error($v['goods_name'].'| 入库失败！');
				}
			}
		}
		$trans->commit();
        $return['message']='入库成功!';
        $return['status']=true;    
        $this->ajaxReturn($return);
    }
	//实收入库（跨境）
    public function arrival_inbound_cross(){
		$trans = M('',C('DB_PRS'),C('DB_DEPOT'));
		$trans->startTrans();   // 开启事务
		$s=M('ArrivalOrderPlan',C('DB_PRS'),C('DB_DEPOT'));
		$m=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		$n=M('Goods',C('DB_PRS'),C('DB_DEPOT'));
        if(!IS_POST) exit;
        $ck=A('CheckInput');
		$id=$ck->in('计划单id','id','string','',1,0);
        if(empty($id)) exit;//为空
        $arr=explode(',', $id);
		$map['id']=array('in',$arr);
		$plan_list=$s->where($map)->select();
		// file_put_contents('./log/arrival_inbound_cross_11.log',date('Y-m-d H:i:s').var_export($s->getlastsql(),true).PHP_EOL,FILE_APPEND);//日志导出sql
		foreach($plan_list as $ks=>$vs){
			if($vs['inbound_status']==1){
					continue;//已经入库，则继续循环
			}
			$arrival_goods=$m->where(array('plan_id'=>$vs['id']))->select();
			// file_put_contents('./log/arrival_inbound_cross_1.log',date('Y-m-d H:i:s').var_export($m->getlastsql(),true).PHP_EOL,FILE_APPEND);//日志导出sql
			foreach($arrival_goods as $k=>$v){
				if(empty($v['bar_code'])){
					$trans->rollback();
					$this->error('理货报告数据未填写不完整');
				}
				$receive_amount=$v['receive_amount'];//实收数量
				$conforming_p=$v['conforming_p'];//合格品数量
				$nonconforming_p=$v['nonconforming_p'];//残次品数量
				$scrap_one=$v['scrap_one'];//报废品数量
				//where唯一条件:商品编码相同，账册编码相同
				$where['goods_no']=$v['goods_no'];
				$where['manua_id']=$v['manual_id'];
				
				$res=$n->where($where)->find();
				// file_put_contents('./log/arrival_inbound_cross_2.log',date('Y-m-d H:i:s').var_export($n->getlastsql().'&/&/'.$res,true).PHP_EOL,FILE_APPEND);//日志导出sql
				if($res){//库存中已经有此商品，则更新库存数据
					$data=array();
					$data['amount']=array('exp',"amount+$receive_amount");
					$data['conforming_p']=array('exp',"conforming_p+$conforming_p");
					$data['nonconforming_p']=array('exp',"nonconforming_p+$nonconforming_p");
					$data['scrap_one']=array('exp',"scrap_one+$scrap_one");
					//价格-平均价--总价/总数量
					$data['goods_price']=($res['goods_price']*$res['amount']+$v['receive_amount']*$v['price'])/($res['amount']+$v['receive_amount']);
					$ress=$n->where($where)->save($data);
					// echo $n->getlastsql();
					// file_put_contents('./log/arrival_inbound_cross_3.log',date('Y-m-d H:i:s').var_export($n->getlastsql(),true).PHP_EOL,FILE_APPEND);//日志导出sql
					if($ress!==false){
						$m->where(array("id"=>$v['id']))->setField('inbound_status',1);//更新详情入库状态
						$m->where(array("id"=>$v['id']))->setField('bar_code',$res['bar_code']);//更新条形码
						continue;
					}else{
						$trans->rollback();
						$this->error('商品编码'.$v['goods_no'].'| 入库失败！');
					}
				}else{//库存中没有此商品,则添加此商品数据入库存
					$data=array();
					$data['source_no']=$v['source_no'];
					$data['goods_name']=$v['goods_name'];
					$data['goods_no']=$v['goods_no'];
					$data['bar_code']=$v['bar_code'];
					$data['amount']=$receive_amount;
					$data['conforming_p']=$v['conforming_p'];
					$data['nonconforming_p']=$v['nonconforming_p'];
					$data['scrap_one']=$v['scrap_one'];
					$data['goods_price']=$v['price'];
					
					$data['manua_id']=$v['manual_id'];
					if(!empty($v['item_no'])){
						$data['item_no']=$v['item_no'];
					}
					if(!empty($v['item_type'])){
						$data['item_type']=$v['item_type'];
					}
					if(!empty($v['current_type'])){
						$data['current_type']=$v['current_type'];
					}
					if(!empty($v['declare_unit'])){
						$data['declare_unit']=$v['declare_unit'];
					}
					if(!empty($v['unit1'])){
						$data['unit1']=$v['unit1'];
					}
					if(!empty($v['unit2'])){
						$data['unit2']=$v['unit2'];
					}
					$data['goods_spec']=$v['goods_spec'];
					$resss=$n->add($data);
					file_put_contents('./log/arrival_inbound_cross_4.log',date('Y-m-d H:i:s').var_export($n->getlastsql(),true).PHP_EOL,FILE_APPEND);//日志导出sql
					if($resss){
						$m->where(array("id"=>$v['id']))->setField('inbound_status',1);//更新详情入库状态
						continue;
					}else{
						$trans->rollback();
						$this->error('商品编码'.$v['goods_no'].'| 入库失败！');
					}
				}
			}
			$s->where(array("id"=>$vs['id']))->setField('inbound_status',1);//更新入库状态
			// echo $s->getlastsql();
		}
		
		$trans->commit();
        $return['info']='入库成功!';
        $return['status']=true;    
        $this->ajaxReturn($return);
    }
	//其它入库审核
	public function otherInboundExamine(){
		$m=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		$id=I('id');
		$arr=explode(',',$id);
		$list=$m->field('id,bound_cate_code')->where(array('id'=>array('in',$arr)))->select();
		foreach($list as $k=>$v){
			if($v['bound_cate_code']=='OI'){
				$data['status']=1;
				$data['confirm_status']=2;
				$map['id']=$v['id'];
				$res=$m->where($map)->save($data);
				
				if($res!==false){
					continue;
				}else{
					$return['message']='审核失败!';
					$return['status']=false;    
					$this->ajaxReturn($return);
				}
			}else{
				$return['message']='请选择其它入库数据!';
				$return['status']=false;    
				$this->ajaxReturn($return);
			}
		}
		$return['message']='审核成功!';
		$return['status']=true;    
		$this->ajaxReturn($return);
		
	}
}